<template>
  <div>
    <el-tree
      :data="data"
      :show-checkbox="showCheckBox"
      default-expand-all
      node-key="id"
      ref="tree"
      highlight-current
      @node-click="clickNode"
      :props="defaultProps"
      @check="clickOne"
    >
    </el-tree>
  </div>
</template>



<script>
import { menuList,findMenusByRoleId } from '../api/menuMG';
  export default {
    props:['showCheckBox',"roleid"],
    watch:{
      //监听父组件传入子组件的角色id的改变，然后触发方法，去后台查询该角色下有哪些权限
      roleid:{
        immediate: true, // immediate选项可以开启首次赋值监听
        handler(newValue,oldValue){
        this.newRoleId = newValue
        this.getMenusByRoleId(newValue);
      }
      }
    },
    created(){
        this.getMenuList();
    },
    methods: {
      clickOne(e,f){
          let checked = f.checkedKeys
          // 添加半选的值 会有bug
          // let halfChecked = f.halfCheckedNodes
          // for(let ced in halfChecked){
          //   checked.push(halfChecked[ced].id)
          // }
          this.$emit('tranChecked',checked,this.newRoleId)
      },
      //通过角色id去数据库中查询出他拥有的菜单信息
      getMenusByRoleId(roleId){
        findMenusByRoleId(roleId).then(res=>{
          if(res.data.code == 200){
            this.$refs.tree.setCheckedKeys(res.data.data);
          }
        })
      },
      //调用后台的方法
      getMenuList(){
        menuList().then(res=>{
          this.data = res.data.data
        });
      },
      //节点被点击后触发的方法
      clickNode(e){
        this.$emit('editNode',e)
      },
      getCheckedNodes() {
        console.log(this.$refs.tree.getCheckedNodes());
      },
      getCheckedKeys() {
        console.log(this.$refs.tree.getCheckedKeys());
      },
      setCheckedNodes() {
        this.$refs.tree.setCheckedNodes([
          {
            id: 5,
            label: "二级 2-1",
          },
          {
            id: 9,
            label: "三级 1-1-1",
          },
        ]);
      },
      setCheckedKeys() {
        this.$refs.tree.setCheckedKeys([3,4,5,6]);
      },
      resetChecked() {
        this.$refs.tree.setCheckedKeys([]);
      },
    },

    data() {
      return {
        data: [],
        newRoleId:0,
        //配置显示和数据的对应关系 menuname|children自己根据后台返回的数据去调整
        defaultProps: {
          children: "children",
          label: "menuname",
        },
      };
    },
  };
</script>